package com.qianyucc.blog.service;

import com.qianyucc.blog.model.dto.*;
import com.qianyucc.blog.model.entity.*;
import com.qianyucc.blog.model.vo.*;
import com.qianyucc.blog.mapper.*;
import com.qianyucc.blog.utils.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.stereotype.*;

import java.time.*;
import java.util.*;
import java.util.stream.*;

import static com.qianyucc.blog.global.Constants.DEFAULT_DATE_TIME_PATTERN;

/**
 * @author lijing
 * @date 2019-10-17 16:47
 * @description 与留言相关的业务
 */
@Service
public class MessageService {
    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private UserMapper userMapper;

    /**
     * 插入一条留言
     *
     * @param messageDTO 要插入的留言
     */
    public void insMessage(MessageDTO messageDTO) {
        MessageDO messageDO = new MessageDO();
        messageDO.setCreator(messageDTO.getCreatorId());
        messageDO.setContent(messageDTO.getContent());
        messageDO.setGmtCreate(Instant.now().toEpochMilli());
        messageMapper.insMessage(messageDO);
    }

    /**
     * 查询所有留言信息
     *
     * @return 留言列表
     */
    public List<MessageVO> findAllMessages() {
        List<MessageDO> messageDOS = messageMapper.findAll();
        List<MessageVO> messageVOS = messageDOS.stream()
                .sorted(Comparator.comparing(MessageDO::getGmtCreate).reversed())
                .map(messageDO -> {
                    MessageVO messageVO = new MessageVO();
                    messageVO.setCreatorId(messageDO.getCreator());
                    UserDO userDO = userMapper.findById(messageDO.getCreator());
                    if (userDO != null) {
                        messageVO.setCreatorName(userDO.getName());
                        messageVO.setAvatarUrl(userDO.getAvatarUrl());
                    }
                    messageVO.setContent(messageDO.getContent());
                    messageVO.setGmtCreate(Utils.formatDate(messageDO.getGmtCreate(), DEFAULT_DATE_TIME_PATTERN));
                    return messageVO;
                })
                .collect(Collectors.toList());
        return messageVOS;
    }
}
